<template>
  <div class="questionnaire-detail-container">
    <!-- 头部 -->
    <div class="header-bar">
      <van-icon name="arrow-left" class="back-icon" @click="goBack" />
      <h2 class="header-title">问卷详情</h2>
      <div class="header-actions">
        <van-icon name="more-o" size="20" />
        <van-icon name="aim" size="20" style="margin-left: 10px;" />
      </div>
    </div>

    <!-- 问卷介绍 -->
    <div v-if="questionnaire" class="questionnaire-intro">
      <div class="intro-header">
        <h1 class="intro-title">{{ questionnaire.title }}</h1>
        <span class="intro-count">共{{ questionnaire.totalQuestions }}题</span>
      </div>
      <p class="intro-description">{{ questionnaire.description }}</p>
    </div>

    <!-- 题目列表 -->
    <div v-if="questionnaire" class="questions-container">
        <div 
        v-for="question in questionnaire.questions" 
        :key="question.id"
        class="question-card"
      >
        <div class="question-header">
          <span class="question-title">{{ question.id }}、{{ question.title }}</span>
          <span class="question-type" :class="question.type === 'single' ? 'type-single' : question.type === 'multiple' ? 'type-multiple' : 'type-text'">
            {{ question.type === 'single' ? '单选' : question.type === 'multiple' ? '多选' : '文本' }}
          </span>
        </div>

        <!-- 单选题 -->
        <div v-if="question.type === 'single'" class="question-options">
          <van-radio-group 
            :model-value="getAnswer(question.id)" 
            @update:model-value="(value) => setAnswer(question.id, value)"
          >
            <van-radio 
              v-for="(option, index) in question.options" 
              :key="index"
              :name="option"
              class="option-item"
            >
              {{ option }}
            </van-radio>
          </van-radio-group>
        </div>

        <!-- 多选题 -->
        <div v-if="question.type === 'multiple'" class="question-options">
          <van-checkbox-group 
            :model-value="getMultipleAnswer(question.id)" 
            @update:model-value="(value) => setMultipleAnswer(question.id, value)"
          >
            <van-checkbox 
              v-for="(option, index) in question.options" 
              :key="index"
              :name="option"
              class="option-item"
            >
              {{ option }}
            </van-checkbox>
          </van-checkbox-group>
        </div>

        <!-- 文本题 -->
        <div v-if="question.type === 'text'" class="question-text">
          <van-field
            v-model="textAnswers[question.id]"
            type="textarea"
            placeholder="请输入您的意见或建议"
            rows="4"
            @blur="setTextAnswer(question.id, textAnswers[question.id])"
          />
        </div>
      </div>
    </div>

    <!-- 提交按钮 -->
    <div v-if="questionnaire" class="submit-container">
      <van-button 
        type="primary" 
        block 
        size="large"
        class="submit-btn"
        @click="handleSubmit"
      >
        提交
      </van-button>
    </div>

    <!-- 无数据提示 -->
    <div v-else class="no-data">
      <van-empty description="问卷不存在" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast, showConfirmDialog } from 'vant'
import { getQuestionnaireById, getAnswers, saveAnswers } from './data'

const router = useRouter()
const route = useRoute()

const questionnaireId = computed(() => Number(route.params.id))
const questionnaire = computed(() => getQuestionnaireById(questionnaireId.value))

// 存储答案
const answers = ref<Record<number, string[] | string>>({})
const textAnswers = ref<Record<number, string>>({})

// 初始化答案（从localStorage加载）
onMounted(() => {
  if (!questionnaire.value) return
  
  const savedAnswers = getAnswers(questionnaireId.value)
  if (savedAnswers) {
    answers.value = savedAnswers
    // 初始化文本答案
    Object.keys(savedAnswers).forEach(key => {
      const qId = Number(key)
      const question = questionnaire.value?.questions.find(q => q.id === qId)
      if (question?.type === 'text') {
        textAnswers.value[qId] = savedAnswers[qId] as string || ''
      }
    })
  }
})

// 获取单选题答案
const getAnswer = (questionId: number): string => {
  const answer = answers.value[questionId]
  return Array.isArray(answer) ? answer[0] || '' : answer || ''
}

// 设置单选题答案
const setAnswer = (questionId: number, value: string) => {
  answers.value[questionId] = value
  saveAnswers(questionnaireId.value, answers.value)
}

// 获取多选题答案
const getMultipleAnswer = (questionId: number): string[] => {
  const answer = answers.value[questionId]
  return Array.isArray(answer) ? answer : []
}

// 设置多选题答案
const setMultipleAnswer = (questionId: number, value: string[]) => {
  answers.value[questionId] = value
  saveAnswers(questionnaireId.value, answers.value)
}

// 设置文本题答案
const setTextAnswer = (questionId: number, value: string) => {
  answers.value[questionId] = value
  saveAnswers(questionnaireId.value, answers.value)
}

// 验证必填题
const validateAnswers = (): boolean => {
  if (!questionnaire.value) return false
  
  for (const question of questionnaire.value.questions) {
    if (question.required) {
      const answer = answers.value[question.id]
      if (!answer || (Array.isArray(answer) && answer.length === 0) || answer === '') {
        showToast(`请回答第${question.id}题`)
        return false
      }
    }
  }
  return true
}

// 提交问卷
const handleSubmit = async () => {
  if (!validateAnswers()) {
    return
  }

  try {
    await showConfirmDialog({
      title: '确认提交',
      message: '提交后将无法修改，确认提交吗？',
      confirmButtonText: '确认提交',
      cancelButtonText: '取消'
    })

    // 提交成功，跳转到成功页面
    router.push(`/questionnaire/${questionnaireId.value}/success`)
  } catch {
    // 用户取消
  }
}

const goBack = () => {
  router.back()
}
</script>

<style scoped>
.questionnaire-detail-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 80px;
}

.header-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px 20px;
  background-color: #fff;
  border-bottom: 1px solid #f0f0f0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.back-icon {
  font-size: 20px;
  cursor: pointer;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  margin: 0;
  flex: 1;
  text-align: center;
}

.header-actions {
  display: flex;
  align-items: center;
}

.questionnaire-intro {
  background-color: #fff;
  padding: 20px;
  margin-bottom: 15px;
}

.intro-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.intro-title {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin: 0;
  flex: 1;
}

.intro-count {
  font-size: 14px;
  color: #999;
  margin-left: 10px;
}

.intro-description {
  font-size: 14px;
  color: #666;
  line-height: 1.6;
  margin: 0;
}

.questions-container {
  padding: 0 15px;
}

.question-card {
  background-color: #fff;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
}

.question-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  flex: 1;
  line-height: 1.5;
}

.question-type {
  font-size: 12px;
  padding: 4px 10px;
  border-radius: 12px;
  margin-left: 10px;
  white-space: nowrap;
}

.type-single {
  background-color: #e3f2fd;
  color: #1976d2;
}

.type-multiple {
  background-color: #f3e5f5;
  color: #7b1fa2;
}

.type-text {
  background-color: #e8f5e9;
  color: #388e3c;
}

.question-options {
  margin-top: 10px;
}

.option-item {
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.option-item:last-child {
  border-bottom: none;
}

.question-text {
  margin-top: 10px;
}

.submit-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 15px 20px;
  background-color: #fff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  z-index: 100;
}

.submit-btn {
  border-radius: 25px;
  font-size: 16px;
  font-weight: 600;
}

.no-data {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 50vh;
}
</style>

